package cn.yedong.basic.controller;

import cn.yedong.basic.dto.PhoneCodeDto;
import cn.yedong.basic.exception.BusinessException;
import cn.yedong.basic.service.IVerifyCodeService;
import cn.yedong.basic.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/verifyCode")
public class VerifyCodeController {
    @Autowired
    private IVerifyCodeService verifyCodeService;

    /**
     * 获取图形验证码
     * @param key
     * @return
     */
    @GetMapping("/image/{key}")
    public AjaxResult getImageCode(@PathVariable("key") String key){
        try {
            String base64Str = verifyCodeService.getImageCode(key);
            //将生成的base64编码的图片字符串返回到前端
            return AjaxResult.me().setObj(base64Str);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙，请稍后再试！");
        }
    }

    /**
     * 发送手机验证码【手机注册】
     * @param phoneCodeDto
     * @return
     */
    @PostMapping("/phone")
    public AjaxResult getPhoneCode(@RequestBody PhoneCodeDto phoneCodeDto){
        try {
            verifyCodeService.sendPhoneCode(phoneCodeDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            return new AjaxResult(false,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙，请稍后再试！");
        }
    }

    /**
     * 获取手机验证码【绑定微信】
     * @param phoneCodeDto
     * @return
     */
    @PostMapping("/wechatBinder")
    public AjaxResult binderWechat(@RequestBody PhoneCodeDto phoneCodeDto){
        try {
            verifyCodeService.binderWechat(phoneCodeDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            return new AjaxResult(false,e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"网络繁忙，请稍后再试！");
        }
    }
}
